package com.keyboard.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.ViewTreeObserver;
import android.widget.RelativeLayout;

import java.util.ArrayList;

public class ResizeLayout extends RelativeLayout {

    private static final String TAG = "ResizeLayout";
    private Context mContext;
    private int mMaxParentHeight = 0;
    private int mOldh = -1;
    private int mNowh = -1;
    private int mScreenHeight = 0;

    public ResizeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (mScreenHeight == 0) {
                    mScreenHeight = ((Activity) mContext).getWindow().getDecorView().getRootView().getHeight();
                }

                Rect r = new Rect();
                ((Activity) mContext).getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                int heightDifference = mScreenHeight - r.bottom;

                mNowh = heightDifference;
                if (mOldh != -1 && mNowh != mOldh && mListener != null) {
                    // 弹出软键盘
                    if (mNowh > 0) {
                        mListener.OnSoftPop(heightDifference);
                    }
                    // 隐藏软键盘
                    else if (mNowh == 0) {
                        mListener.OnSoftClose(0);
                    }
                }
                mOldh = mNowh;
            }
        });
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        if (mMaxParentHeight == 0) {
            mMaxParentHeight = h;
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mMaxParentHeight != 0) {
            int heightMode = MeasureSpec.getMode(heightMeasureSpec);
            int expandSpec = MeasureSpec.makeMeasureSpec(mMaxParentHeight, heightMode);
            super.onMeasure(widthMeasureSpec, expandSpec);
            return;
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    private OnResizeListener mListener;

    public void setOnResizeListener(OnResizeListener l) {
        mListener = l;
    }

    public interface OnResizeListener {
        /**
         * 软键盘弹起
         */
        void OnSoftPop(int height);

        /**
         * 软键盘关闭
         */
        void OnSoftClose(int height);
    }
}